package com.quickask.operate.encode;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;

/**
 * Created by NaSa on 2015/10/7.
 */
public class AES_Encode {


    /**
     * 加密函数
     *
     * @param encodeText 加密的内容
     * @param key        密钥
     * @return 返回二进制字符数组
     * @throws Exception
     */
    public byte[] enCrypt(String encodeText, String key) throws Exception {
        KeyGenerator keyGenerator;
        SecretKey desKey;
        Cipher cipher;
        byte[] cByte;
        String str = encodeText;
        keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128, new SecureRandom(key.getBytes()));
        desKey = keyGenerator.generateKey();
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, desKey);
        cByte = cipher.doFinal(str.getBytes("UTF-8"));
        return cByte;
    }

    /**
     * 解密函数
     *
     * @param bytes 加密过的二进制字符数组
     * @param key   密钥
     * @return 返回未加密的内容
     * @throws Exception
     */
    public String deCrypt(byte[] bytes, String key) throws Exception {
        KeyGenerator keyGenerator;
        SecretKey desKey;
        Cipher cipher;
        byte[] cByte;
        keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128, new SecureRandom(key.getBytes()));
        desKey = keyGenerator.generateKey();
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, desKey);
        cByte = cipher.doFinal(bytes);
        return new String(cByte, "UTF-8");
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr 16进制字符串
     * @return 二进制数组
     */
    public byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i << 2, i << 2 + 1), 2 << 4);
            int low = Integer.parseInt(hexStr.substring(i << 2 + 1, i << 2 + 2), 2 << 4);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 二进制转16进制
     *
     * @param buf 二进制数组
     * @return 16进制字符串
     */
    public String parseByte2HexStr(byte buf[]) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            stringBuffer.append(hex.toUpperCase());
        }
        return stringBuffer.toString();
    }

    public void test(String[] args) throws Exception {
        // TODO Auto-generated method stub
        String str = "user=admin&pwd=admin";
        String key = "12345678";
        String encrytStr;
        byte[] encrytByte;

        byte[] byteRe = enCrypt(str, key);

        //加密过的二进制数组转化成16进制的字符串
        encrytStr = parseByte2HexStr(byteRe);
        System.out.println("加密后：" + encrytStr);

        //加密过的16进制的字符串转化成二进制数组
        encrytByte = parseHexStr2Byte(encrytStr);
        System.out.println("解密后：" + deCrypt(encrytByte, key));


    }
}
